require('../../assets/css/index.less');
// 当前页面样式
require('./register.less');

// 工具函数 utils
const dom = require('../../utils/dom');

var CaptchaMini = require("captcha-mini");
// 验证码
const validator = require('../../utils/validator');
var { isAcount, ispwd } = validator;
// ajax
var https = require("../../utils/https");
console.log(https);
// 
dom.ready(function() {
    // 验证码
    let captcha1 = new CaptchaMini();
    var str = ''
    captcha1.draw(document.querySelector('#captcha1'), r => {
        console.log(r, '验证码1');
        str = r.toLowerCase()
    });
    // 表单验证
    var btn = dom.getEle(".btn");
    var mox = document.querySelector(".model-x");
    var moy = document.querySelector(".model-y");

    var acount = dom.getEle(".acount");
    var yzm = dom.getEle(".yzm");
    var pwd = dom.getEle(".pwd");
    var pwd2 = dom.getEle(".pwd2");
    // console.log(btn, acount, pwd, pwd2);

    btn.addEventListener("click", function() {
        // console.log(acount.value);
        console.log(str);
        //手机号
        if (acount.value == '') {
            alert("请输入手机号/账号");
        } else if (!isAcount(acount.value)) {
            alert("手机号/账号输入有误")
        }
        // 验证码
        else if (yzm.value == '') {
            alert("验证码不能为空")
        } else if (yzm.value.toLowerCase() != str) {
            alert("验证码有误")
        }
        //密码
        else if (pwd.value == '') {
            alert("密码不能为空")
        } else if (!ispwd(pwd.value)) {
            alert("密码输入有误")
        }
        // 确认密码
        else if (pwd2.value != pwd.value) {
            alert("两次输入密码不一致")
        } else {
            https.post("/api/user/isExist", {
                account: acount.value,
            }, function(res) {
                if (res.errno == 0) {

                    https.post("/api/user/register", {
                        account: acount.value,
                        password: pwd.value
                    }, function(res) {
                        if (res.errno == 0) {
                            // alert("注册成功")
                            moy.style.display = "block"
                        } else {
                            alert("注册失败")
                        }
                    })
                } else {
                    alert("用户名已存在")
                }
            })

        }

    });
    moy.addEventListener("click", function() {
        location.href = "./login.html"
    })
})